package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.name.User;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	private static String norect = "1";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		KXUtil.getUsers(new Filter(){
			public boolean access(User user) {
				return true;
			}
		}, resp);
	}
	
	public static void initPage(List<String> emails, HttpServletResponse resp)
			throws IOException {
		resp.getWriter().println("<form name='form' method='post' action='/kx/login'>");
		for (String email: emails) {
			KXClient client = KXClient.getInstance(email, true);
			String encypt = client.getEncypt();
			String rcode = Math.random() + "_" + System.currentTimeMillis();
			String imgUrl = "/interface/regcreatepng.php?norect=" + norect + "&randnum="
					+ rcode + "&cookiekey=" + email + "&isnew=true";
			resp.getWriter().println("<input type=hidden name='cookiekey' value='" + email + "'>" + email);
			resp.getWriter().println("<input type=hidden name='encypt' value='" + encypt + "'>");
			resp.getWriter().println("<input type=hidden name='rcode' value='" + rcode + "'>");
			resp.getWriter().println("<input type=text name='code' value=''>");
			resp.getWriter().println("<img src='" + imgUrl + "' /><br>");
		}
		resp.getWriter().println("<input type=submit name='submit' value='login'>");
		resp.getWriter().println("</form>");
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<String> emailArray = new ArrayList<String>();
		String[] emails = req.getParameterValues("cookiekey");
		String[] rcodes = req.getParameterValues("rcode");
		String[] codes = req.getParameterValues("code");
		String[] encypts= req.getParameterValues("encypt");
		for (int i = 0, n = emails.length; i < n; i++) {
			KXClient client = KXClient.getInstance(emails[i], true);
			client.login(rcodes[i], codes[i], encypts[i]);
			if (!client.isLogined()) {
				emailArray.add(emails[i]);
			}
		}
		if (emailArray.size() > 0) {
			initPage(emailArray, resp);
		} else {
			resp.getWriter().println("OK");
		}
	}
}
